//写一个函数，求两个整数之和，要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。 
//
// 
//
// 示例: 
//
// 输入: a = 1, b = 1
//输出: 2 
//
// 
//
// 提示： 
//
// 
// a, b 均可能是负数或 0 
// 结果不会溢出 32 位整数 
// 
//
// Related Topics 位运算 数学 👍 415 👎 0


package leetcode.editor.cn;

// [剑指 Offer 65]不用加减乘除做加法

public class BuYongJiaJianChengChuZuoJiaFaLcof_JianZhiOffer65 {
    public static void main(String[] args) {
        Solution solution = new BuYongJiaJianChengChuZuoJiaFaLcof_JianZhiOffer65().new Solution();
        System.out.println(solution.add(23, 7));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int add(int a, int b) {
            int n = a;
            int c;
            while (b != 0) {
                c = (n & b) << 1;
                n = n ^ b;
                b = c;
            }
            return n;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    class Solution1 {
        public int add(int a, int b) {
            int ans = 0;
            int flag = 0;
            int[] tmp;
            for (int i = 0; i < 32; i++) {
                tmp = fullAdd((a >> i), (b >> i), flag);
                ans ^= (tmp[0] << i);
                flag = tmp[1];
            }
            return ans;
        }

        public int[] halfAdd(int a, int b) {
            int[] ans = new int[2];
            ans[0] = (a ^ b) & 1;
            ans[1] = (a & b) & 1;
            return ans;
        }

        public int[] fullAdd(int a, int b, int c) {
            int[] ans = new int[2];
            int[] h1 = halfAdd(a, b);
            int[] h2 = halfAdd(h1[0], c);
            ans[0] = h2[0];
            ans[1] = h1[1] | h2[1];
            return ans;
        }
    }
}